/**
* @author:kellen
* @modified:
* @company:achivo-gz
* @created on:
* @modified on:
*/

package com.sasis.webapp.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.acegisecurity.providers.encoding.Md5PasswordEncoder;
import org.acegisecurity.providers.encoding.MessageDigestPasswordEncoder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.sasis.Constants;
import com.sasis.model.User;
import com.sasis.service.UserManager;
import com.sasis.util.ConvertUtil;
import com.sasis.webapp.form.LoginForm;





public final class UserLoginAction extends Action {

	protected final Log log = LogFactory.getLog(getClass());
   
    public ActionForward execute(ActionMapping mapping, ActionForm form,
                                HttpServletRequest request,
                                HttpServletResponse response)
    throws Exception {
        if (log.isDebugEnabled()) {
            log.debug("Entering 'UserLoginAction' method");
        }
        
		ApplicationContext ctx = WebApplicationContextUtils
			.getRequiredWebApplicationContext(request.getSession().getServletContext());
		LoginForm loginForm = (LoginForm)form; 
		String username = request.getParameter("j_username");
		String password = request.getParameter("j_password");
		loginForm.setName(username);
		loginForm.setPassword(password);
		log.debug(loginForm);
	    User user = (User)ConvertUtil.convert(loginForm);
	  
	    log.debug(user);
	   
	    Md5PasswordEncoder encoder = new Md5PasswordEncoder();
	    String encryptedPassword = encoder.encodePassword(password, null);
	    
		UserManager umgr = (UserManager)ctx.getBean("userManager");
	     User	tempuser =umgr.getUser(username,encryptedPassword);
	     if(tempuser==null)
	     {
	    	 log.debug("***************************login failed");
	    	 return mapping.findForward("failed");
	     }
          
	     else{
	    	 System.out.println("^^^^^^^^^^^^^^^^^^^");
               //request.getSession().setAttribute(Constants.CURUSER_KEY, "true");
               //request.getSession().setAttribute("user", tempuser);
               return mapping.findForward("success");
	     }
    }
    
	
}
